package com.jinzhu.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jinzhu.dao.ClazzMapper;
import com.jinzhu.dao.StuMapper;
import com.jinzhu.pojo.*;
import com.jinzhu.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class StuServiceImpl implements StuService {
    @Autowired
    StuMapper stuMapper;
    @Autowired
    ClazzMapper clazzMapper;

    // 根据内容分页查询学员
    @Override
    public PageBean AllStu1(String name, Integer degree, Integer clazzId, Integer begin, Integer end, Integer StuPage, Integer StuPageSize) {
        PageHelper.startPage(StuPage, StuPageSize);
        List<Student> students = stuMapper.AllStu1(name, degree, clazzId, begin, end);
        Page<Student> empPage = (Page<Student>) students;
        PageBean pageBean = new PageBean(empPage.getTotal(), empPage.getResult());
        return pageBean;
    }

    // 根据批量ID删除学员
    @Override
    public Integer delete(Integer[] ids) {
        return stuMapper.delete(ids);

    }

    //        if (StringUtils.hasLength(student.getName()) || StringUtils.hasLength(student.getNo()) || student.getGender()!=null || StringUtils.hasLength(student.getPhone()) || student.getDegree()!=null || student.getClazzId()!=nullStringUtils.hasLength(student.getName())||StringUtils.hasLength(student.getNo())
    //
    // 添加学员
    @Override
    public Integer add(Student student) {
        // 参数校验
        if (student == null) {
            throw new IllegalArgumentException("Student 对象不能为空");
        }

        // 统一设置当前时间
        LocalDateTime now = LocalDateTime.now();
        student.setCreateTime(now);
        student.setUpdateTime(now);

        // 设置默认违规信息
        if (student.getViolationCount() == null) {
            student.setViolationCount((short) 0);
        }
        if (student.getViolationScore() == null) {
            student.setViolationScore((short) 0);
        }

        return stuMapper.add(student);
    }

    // 根据ID查询学员
    @Override
    public Student get(Integer id) {
        Student student = stuMapper.get(id);
        return student;
    }


    //    @Override
//    public Integer update(Student student) {
//        if (student.getId()!=null || StringUtils.hasLength(student.getName())
//                || StringUtils.hasLength(student.getNo()) || StringUtils.hasLength(student.getPhone())
//                || student.getGender()!=null || student.getDegree()!=null || student.getClazzId()!=null
//                || student.getViolationCount()!=null || student.getViolationScore()!=null){
//            student.setUpdateTime(LocalDateTime.now());
//            return stuMapper.update(student);
//        }
//        return 0;
//    }
    // 修改学员
    @Override
    public Integer update(Student student) {
        if (student == null || student.getId() == null) {
            throw new IllegalArgumentException("学员ID不能为空");
        }
        student.setUpdateTime(LocalDateTime.now());
        return stuMapper.update(student);
    }


// 违纪处理

    // 违纪处理
//    @Override
//    public Integer violation(Integer id, Integer score) {
//        Student studentById = stuMapper.get(id);
//        studentById.setViolationScore((short)(studentById.getViolationScore()-score));
//        studentById.setUpdateTime(LocalDateTime.now());
//        return stuMapper.update(studentById);
//    }

    @Override
    public Integer violation(Integer id, Integer score) {
        Student student = stuMapper.get(id);
        if (student == null) {
            throw new IllegalArgumentException("学员不存在");
        }
        try {
            // 强制最小值为 0（适用于无负分逻辑）
            //Short.MIN_VALUE 表示 short 类型的最小值： -32768
            //Short.MAX_VALUE 表示 short 类型的最大值： 32767
            //student.getViolationScore() 获取当前学生的违规分数；
            //score 是传入的要增加或减少的分数（可为负数）；
            //Math.max(Short.MIN_VALUE, ...) 确保相加后的结果不低于 short 的最小允许值，防止溢出错误；
            //最终将结果强制转为 short 类型后设置回学生对象
            int newScore = Math.max(Short.MIN_VALUE, student.getViolationScore() + score);
            student.setViolationScore((short) newScore);
            student.setUpdateTime(LocalDateTime.now());

            return stuMapper.update(student);
        } catch (Exception e) {
            System.out.println("数据异常负数不能为负数");
        }
        return 0;
    }

    /**
     * 获取学生学历数据
     * <p>
     * 本方法从数据库中获取学生的学历分布情况，并将数据处理后以列表的形式返回
     * 每个学历层次对应一个名称，并计算每个学历层次的学生数量
     *
     * @return 学历数据列表，每个元素是一个包含学历名称和对应学生数量的映射
     */
    @Override
    public List<Map<String, Object>> studentDegreeData() {

        // 从数据库中获取学生学历数据，并进行流处理
        List<Map<String, Object>> studentDegreeData = stuMapper.studentDegreeData().stream().map(item -> {
            // 创建一个新的映射来存储处理后的学生学历数据
            Map<String, Object> newMap = new HashMap<>();

            // 获取当前项的学历值，并检查是否为null
            Integer degree = (Integer) item.get("degree");
            if (degree != null) {
                // 根据学历值映射到相应的学历名称
                if (degree == 1) {
                    newMap.put("name", "本科");
                } else if (degree == 2) {
                    newMap.put("name", "专科");
                } else if (degree == 3) {
                    newMap.put("name", "高中");
                } else if (degree == 4) {
                    newMap.put("name", "初中");
                } else if (degree == 5) {
                    newMap.put("name", "小学");
                }
            }

            // 将学生数量添加到新的映射中
            newMap.put("value", item.get("count(id)"));

            // 返回处理后的映射
            return newMap;
        }).toList();

        // 返回处理后的学生学历数据列表
        return studentDegreeData;
    }
    //班级人数统计
    @Override
    public Map<String, Object> studentCountData() {
        List<String>classNames = new ArrayList<>();
        List<Object>stuCounts = new ArrayList<>();
        stuMapper.studentCountData().forEach(item->{
            Number classIdNum= (Number) item.get("clazzId");
            int classId=classIdNum.intValue();
            Clazz clazz = clazzMapper.get(classId);
            if (clazz== null){
                classNames.add("未知");
                stuCounts.add(item.get("count(id)"));
                return;
            }
            classNames.add(clazz.getName());
            stuCounts.add( item.get("count(id)"));
        });
        Map<String,Object> result = new LinkedHashMap<>();
        result.put("classNames",classNames);
        result.put("stuCounts",stuCounts);
        return result;
    }
}
